var app_id;
var scope = 'snsapi_userinfo';
var user_info = get("user_info_openid");
var code = '';
var open_id
var avatar
var nickname
var host = ''

host = getHost(location.href)
authorizeInit()

function getHost(href){
	return href.split('?')[0]
}

// 获取code
function getCode(){
	return getUrlParam('code')
}

// 获取appId
function getAppId(){
	$.ajax({
		url: 'http://szhqg.horsevision.cn/weixin/oauth/params',
		type: "GET",
		dataType: "json",
		async: false,
		data: {},
		success: function (res) {
			if (res.code == 200) {
				app_id = res.data.appid;
				
				// 获取CODE
				var redirect_url2 = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + app_id + '&redirect_uri=' + location.href + '&response_type=code&scope=' + scope + '&state=#wechat_redirect';
				window.location.href = redirect_url2;
			}
		}
	});
	
	return app_id
}

// 授权
function authorize(){
	$.ajax({
		url: 'http://szhqg.horsevision.cn/weixin/oauth/callback',
		type: 'GET',
		dataType: 'json',
		async: false,
		data: {
			code: code
		},
		success: function (res) {
			user_info = JSON.stringify(res.data);
			open_id = res.data.open_id
			avatar = res.data.avatar
			nickname = res.data.nickname
			set("user_info_openid", res.data.open_id, 3);
			set("user_info_avatar", encodeURI(res.data.avatar), 3);
			set("user_info_nickname", encodeURI(res.data.nickname), 3);
			location.href = host
		}
	})
}

// 授权初始化
function authorizeInit(){
	var user_info = get("user_info_openid")
	
	if ( !user_info ) {
		// 从url中获取code
		code = getCode();
	
	  if (!code) {
			// 取APPID
			var app_id = getAppId()
			// 跳转到指定地址，获取CODE
			location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + app_id + '&redirect_uri=' + location.href + '&response_type=code&scope=' + scope + '&state=#wechat_redirect';
	  } else {
			// 授权
	    authorize()
	  }
	}
}





function getUrlParam(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

function set(name, value, time){
	const date = new Date();

	date.setDate(date.getDate() + time);
	document.cookie = `${name}=${value};expires=${date}`;
}

function remove(name){
	// 设置已过期，系统会立刻删除cookie
	set(name, '1', -1);
}

function get(name){
	const arr = document.cookie.replace(/\s/g, '').split(';');

	for(let i = 0, len = arr.length; i < len; i++){
		let tempArr = arr[i].split('=');

		if(tempArr[0] === name) return decodeURIComponent(tempArr[1]);
	}

	return '';
}